import { _decorator, Component, Director, director, instantiate, js, Node } from 'cc';
import { BaseComponent } from '../UIManager/BaseComponent';
const { ccclass, property } = _decorator;


export class TopManager {
    private constructor() {
        director.once(Director.EVENT_AFTER_SCENE_LAUNCH, this.Init, this);
    }

    /** 初始化方法 */
    private Init(): void {
        this.Root = director.getScene().getChildByName('Canvas').getChildByName("PopManager");
    }

    /** 单例实例 */
    public static readonly instance: TopManager = new TopManager();

    //场景节点
    private Root: Node = null;

    //已添加弹窗列表
    private TopList: Map<string, BaseComponent> = new Map();

    //当前场景
    private CurrentTop: BaseComponent | null = null;

    /**
     * 显示弹窗
     * @param 类名称
     */
    public ShowTop(_classname: string, _data: { key: string, value: any } = null) {

        let view: BaseComponent = this.TopList.get(_classname);
        const UIClass = js.getClassByName(_classname) as { new(): BaseComponent };

        if (!view) {
            const node: Node = instantiate(app.resManager.Prefabs[_classname]);
            view = node.getComponent(UIClass);
            this.TopList.set(_classname, view);
        }

        //如果有场景则隐藏掉
        if (this.CurrentTop) {
            this.CurrentTop.node.removeFromParent();
        }

        this.CurrentTop = view;

        this.CurrentTop.node.parent = this.Root;
        this.CurrentTop.node.setSiblingIndex(this.Root.children.length - 1);

    }

    /**
     * 隐藏弹窗
     */
    public HideTop(_classname: string) {
        let view: BaseComponent = this.TopList.get(_classname);
        if (view) {
            view.node.removeFromParent();
        }
    }

}

/** 导出单例实例 */
export const topManager = TopManager.instance;


